<template>
  <div class="m-25 mt-65">
    <div class="normal-box-mod">
      <div class="normal-box-hd clearfix">
        <div class="normal-box-title">
          <div class="decorate-square"></div>
          <h2>广告管理</h2>
        </div>
      </div>
      <div class="normal-box-bd">
        <div class="normal-list-page-mod">
          <div class="mb-2">
            <Button-group>
              <Button custom-icon="iconfont icon-shanchusekuai"
                      size="small"
                      type="error"
                      @click="batchDel">
                删除
              </Button>
              <Button custom-icon="iconfont icon-fangkuai2"
                      size="small"
                      type="primary"
                      @click="showCreateModal">
                新建
              </Button>
            </Button-group>
          </div>
          <div class="normal-list-page-bd">
            <Table border
                   :loading="list.loading"
                   :columns="list.columns"
                   :data="list.tableData"
                   @on-selection-change="selectionChange">
              <template slot-scope="{ row }"
                        slot="desc">
                <Button type="primary"
                        size="small"
                        @click="openDesc(row.content)">查看</Button>
              </template>
            </Table>
          </div>
          <div class="normal-list-page-ft clearfix">
            <Page class="fr"
                  :total="queryData.totalRecord"
                  :page-size="queryData.pageSize"
                  :current="queryData.page"
                  @on-change="changePage"
                  @on-page-size-change="onPageSizeChange"
                  show-elevator
                  show-total
                  show-sizer></Page>
          </div>
        </div>
        <Modal v-model="modal.mallAdvertising.bigPicVisible"
               width="1000px">
          <img :src="modal.mallAdvertising.bigPicUrl"
               style=" width:100%;height:100%" />
          <div slot="footer" />
        </Modal>
        <!--新建&修改-->
        <Modal v-model="modal.mallAdvertising.isShow"
               :loading="modal.mallAdvertising.loading"
               :mask-closable="false"
               :title="modal.mallAdvertising.title"
               @on-ok="postData"
               width="800px">
          <Form ref="systemFrom"
                :model="modal.mallAdvertising.formData"
                :rules="modal.mallAdvertising.rules"
                :label-width="120">
            <FormItem label="广告标题"
                      prop="name">
              <Input placeholder="请输入广告标题"
                     maxlength="100"
                     v-model="modal.mallAdvertising.formData.name"
                     style="width:300px;" />
            </FormItem>
            <FormItem label="上传图片"
                      prop="url">
              <upload-image v-if="modal.mallAdvertising.isShow"
                            ref="upload"
                            :uploadList.sync="modal.mallAdvertising.formData.uploadList"
                            @imageupload="calcImg"
                            imgSize="1"></upload-image>
            </FormItem>
            <FormItem label="广告类型"
                      prop="position">
              <Select v-model="modal.mallAdvertising.formData.position"
                      class="mr-10"
                      :clearable=flog
                      style="width:100px">
                <Option v-for="item in modal.positionList"
                        :value="item.id"
                        :key="item.id">{{item.name}}</Option>
              </Select>
            </FormItem>
            <FormItem label="活动内容"
                      prop="content">
              <wang-editor v-if="modal.mallAdvertising.isShow"
                           :value="modal.mallAdvertising.formData.content"
                           @change="(v)=>{modal.mallAdvertising.formData.content=v}"></wang-editor>
              <!-- <Input type="textarea" placeholder="请输入活动内容" maxlength="100000" v-model="modal.mallAdvertising.formData.content" style="width:300px;"/> -->
            </FormItem>
            <!--<FormItem label="广告开始时间"-->
                      <!--prop="startTime">-->
              <!--<DatePicker v-model="modal.mallAdvertising.formData.startTime"-->
                          <!--@on-change="modal.mallAdvertising.formData.startTime=$event"-->
                          <!--type="date"-->
                          <!--format="yyyy-MM-dd HH:mm:ss"-->
                          <!--placeholder="请选择广告开始时间"-->
                          <!--style="width: 200px"></DatePicker>-->
            <!--</FormItem>-->
            <!--<FormItem label="广告结束时间"-->
                      <!--prop="endTime">-->
              <!--<DatePicker v-model="modal.mallAdvertising.formData.endTime"-->
                          <!--@on-change="modal.mallAdvertising.formData.endTime=$event"-->
                          <!--type="date"-->
                          <!--format="yyyy-MM-dd HH:mm:ss"-->
                          <!--placeholder="请选择广告结束时间"-->
                          <!--style="width: 200px"></DatePicker>-->
            <!--</FormItem>-->
            <FormItem label="是否启动"
                      prop="enabled">
              <i-switch :size="large"
                        v-model="modal.mallAdvertising.formData.enabled"
                        :value="modal.mallAdvertising.formData.enabled">
                <span slot="open">开</span>
                <span slot="close">关</span>
              </i-switch>
            </FormItem>
          </Form>
        </Modal>
          <!-- 查看详情 -->
        <Modal v-model="showDesc"
               title="详情"
               width="600px">
           <div style="max-width:100%" v-html="descHtml"></div>
        </Modal>
      </div>
    </div>
  </div>
</template>
<script>
import MallAdvertisingApi from '@/api/mall/MallAdvertising.js'
import { Message } from 'iview'
import WangEditor from '@/components/Editor/WangEditor.vue'
import Uploadoss from '@/components/uploadoss'
import uploadImage from '@/components/upload-image/upload-image'
import global from '@/assets/js/global'
export default {
  name: 'mallAdvertising',
  components: {
    uploadImage,
    WangEditor,
    Uploadoss
  },
  data () {
    return {
      // 弹出层数据
      modal: {
        positionList: [
          { id: 1, name: '积分商城' },
          { id: 2, name: '新闻快讯' },
          { id: 3, name: '政策制度' },
          { id: 4, name: '分类知识' },
          { id: 5, name: '最新资讯' }
        ],
        mallAdvertising: {
          isShow: false,
          bigPicVisible: false,
          loading: true,
          bigPicUrl: '',
          type: 'create', // create 新建，update 修改
          title: '新建',
          rules: {
            name: [
              {
                required: true,
                message: '请填写广告标题',
                trigger: 'blur'
              }
            ],
            content: [
              {
                required: true,
                message: '请填写活动内容',
                trigger: 'blur'
              }
            ],
            position: [
              {
                type: 'number',
                required: true,
                message: '请选择接广告类型',
                trigger: 'change'
              }
            ],
            url: [
              { required: true, message: '请上传图片', trigger: 'change' }
            ]
          },
          formData: {}
        }
      },
      // 列表
      list: {
        loading: false,
        selections: [],
        // 列表展示数据
        tableData: [],
        // 表格表头
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          /** 开始自动生成 */
          { title: 'id', key: 'id', align: 'center', minWidth: 50 },
          { title: '广告标题', key: 'name', align: 'center', minWidth: 100 },
          {
            title: '广告图片',
            key: 'url',
            align: 'center',
            minWidth: 100,
            render: (h, params) => {
              return h('img', {
                attrs: {
                  src: params.row.url
                },
                style: {
                  width: '100%',
                  height: '35px'
                },
                on: {
                  click: () => {
                    this.showBigPic(params.row.url) // 此处再用一个方法，建一个modal把图放大。
                  }
                }
              })
            }
          },
          {
            title: '类型',
            key: 'position',
            align: 'center',
            minWidth: 80,
            render: (h, params) => {
              if (params.row.position === 1) {
                return h('div', '积分商城')
              } else if (params.row.position === 2) {
                return h('div', '新闻快讯 ')
              } else if (params.row.position === 3) {
                return h('div', '政策制度 ')
              } else if (params.row.position === 4) {
                return h('div', '分类知识 ')
              } else if (params.row.position === 5) {
                return h('div', '最新资讯 ')
              }
            }
          },
          {
            title: '活动内容',
            key: 'content',
            align: 'center',
            minWidth: 130,
            slot: 'desc'
          },
          // {
          //   title: '广告开始时间',
          //   key: 'startTime',
          //   align: 'center',
          //   minWidth: 130
          // },
          // {
          //   title: '广告结束时间',
          //   key: 'endTime',
          //   align: 'center',
          //   minWidth: 130
          // },
          {
            title: '状态',
            key: 'enabled',
            align: 'center',
            minWidth: 50,
            render: (h, params) => {
              return h('div', [
                h('i-switch', {
                  props: {
                    value: params.row.enabled
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    'on-change': (value) => {
                      this.switch(params.row, value)
                    }
                  }
                })
              ])
            }
          },
          {
            title: '添加时间',
            key: 'createTime',
            align: 'center',
            minWidth: 130
          },
          {
            title: '修改时间',
            key: 'updateTime',
            align: 'center',
            minWidth: 130
          },
          /** 自动生成结束 */
          {
            title: '操作',
            align: 'center',
            minWidth: 150,
            fixed: 'right',
            render: (h, params) => {
              return h('div', { class: 'action-group' }, [
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'left',
                      content: '编辑'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'primary',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            // this.showUpdateModal(params.index);
                            this.showUpdateModal(params.row.id)
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-bianjisekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                ),

                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'right',
                      content: '删除'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'error',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.delData([params.row.id])
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-shanchusekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                )
              ])
            }
          }
        ]
      },
      // 页面查询数据
      queryData: {
        limit: 10,
        page: 1,
        totalRecord: 0,
        name: ''
      },
      showDesc: false,
      descHtml: ''
    }
  },
  methods: {
    showBigPic (item) {
      this.modal.mallAdvertising.bigPicVisible = true
      this.modal.mallAdvertising.bigPicUrl = item
    },
    // 获取列表
    getTableData () {
      const that = this
      MallAdvertisingApi.getPageList(that.queryData)
        .then((res) => {
          console.log(res.data.list)
          that.list.tableData = res.data.list
          that.queryData.totalRecord = res.data.totalRecord
          that.queryData.page = res.data.pageNum
          that.queryData.limit = res.data.pageSize
        })
        .catch((error) => {
          Message.error(error)
        })
    },
    // 修改是否 热门
    switch (data, vlaue) {
      data.enabled = vlaue
      MallAdvertisingApi.update(data.id, data)
        .then((res) => {})
        .catch((error) => {
          Message.error(error)
        })
    },
    // 新建&修改
    postData () {
      const that = this
      that.$refs['systemFrom'].validate((valid) => {
        if (valid) {
          if (!that.modal.mallAdvertising.formData.id) {
            // 新建
            MallAdvertisingApi.add(that.modal.mallAdvertising.formData)
              .then((res) => {
                that.modal.mallAdvertising.loading = false
                if (!res.code) {
                  that.modal.mallAdvertising.isShow = false
                  that.getTableData()
                  that.$Notice.success({
                    title: '保存成功!'
                  })
                } else {
                  that.modal.mallAdvertising.isShow = true
                  that.$Notice.error({
                    title: res.message
                  })
                }
              })
              .catch((error) => {
                Message.error(error)
              })
          } else {
            // 修改
            // that.modal.mallAdvertising.formData.startTime = global.time(
            //   that.modal.mallAdvertising.formData.startTime
            // )
            // that.modal.mallAdvertising.formData.endTime = global.time(
            //   that.modal.mallAdvertising.formData.endTime
            // )
            MallAdvertisingApi.update(
              that.modal.mallAdvertising.formData.id,
              that.modal.mallAdvertising.formData
            )
              .then((res) => {
                that.modal.mallAdvertising.loading = false
                console.log(that.modal.mallAdvertising.formData)
                if (!res.code) {
                  that.modal.mallAdvertising.isShow = false
                  that.getTableData()
                  that.$Notice.success({
                    title: '保存成功!'
                  })
                } else {
                  that.modal.mallAdvertising.isShow = true
                  that.$Notice.error({
                    title: res.message
                  })
                }
              })
              .catch((error) => {
                Message.error(error)
              })
          }
        } else {
          that.modal.mallAdvertising.loading = false
          that.$nextTick(() => {
            that.modal.mallAdvertising.loading = true
          })
        }
      })
    },

    // 删除
    delData (ids) {
      if (!ids.length) {
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        content:
          '<p>您确认删除id为 <strong>' +
          ids.toString() +
          '</strong> 的记录吗?</p><p>删除后将无法撤销，请谨慎操作！</p>',
        loading: true,
        onOk: () => {
          MallAdvertisingApi.del({
            ids: ids
          }).then((res) => {
            this.$Modal.remove()
            if (!res.code) {
              this.$Notice.success({
                title: '删除成功'
              })
              this.queryData.page = 1
              this.getTableData()
            } else {
              this.$Notice.error({
                title: res.message
              })
            }
          })
        }
      })
    },
    // 图片的校验
    calcImg () {
      let imgUrl = this.modal.mallAdvertising.formData.uploadList.map((v) => {
        if (v.length < 1) return v
        v = v.response.res.requestUrls[0]
        return v
      })
      this.modal.mallAdvertising.formData.url = imgUrl[0]
      console.log(this.modal.mallAdvertising.formData.url)
    },
    // 排量删除
    batchDel () {
      let ids = []
      this.list.selections.forEach((element) => {
        ids.push(element.id)
      })
      if (!ids.length) {
        this.$Message.error({
          content: '请先选择要删除的项！',
          duration: 3
        })
      }
      this.delData(ids)
    },

    // 全选，不全选
    selectionChange (args) {
      this.list.selections = args
    },

    // 每页显示记录数变更
    onPageSizeChange (pageSize) {
      this.queryData.limit = pageSize
      this.getTableData()
    },

    // 换页
    changePage (page) {
      this.queryData.page = page
      this.getTableData()
    },

    // 显示新建弹窗
    showCreateModal () {
      this.modal.mallAdvertising.type = 'create'
      this.modal.mallAdvertising.title = '新建'
      this.modal.mallAdvertising.formData = {}
      this.modal.mallAdvertising.isShow = true
      this.$refs.systemFrom.resetFields()
    },

    // 显示修改弹窗
    showUpdateModal (id) {
      this.$refs.systemFrom.resetFields()
      this.modal.mallAdvertising.type = 'update'
      this.modal.mallAdvertising.title = '修改'
      // 不请求后端，直接list取对象
      // this.modal.mallAdvertising.formData = JSON.parse(
      //   JSON.stringify(this.list.tableData)
      // )[index];
      const that = this
      MallAdvertisingApi.getDetail(id)
        .then((res) => {
          console.log(res.data.startTime)
          console.log(res.data.endTime)
          console.log(res.data)
          that.modal.mallAdvertising.formData = res.data
          let item = {
            status: 'finished',
            response: {
              res: {
                requestUrls: []
              }
            }
          }
          if (that.modal.mallAdvertising.formData.url) {
            item.response.res.requestUrls.push(
              that.modal.mallAdvertising.formData.url
            )
            that.modal.mallAdvertising.formData.uploadList = []
            that.modal.mallAdvertising.formData.uploadList.push(item)
          } else {
            that.modal.mallAdvertising.formData.uploadList = []
          }
        })
        .catch((error) => {
          Message.error(error)
        })
      this.modal.mallAdvertising.isShow = true
    },
    openDesc (val) {
      this.descHtml = val
      this.showDesc = true
    }
  },

  created () {
    this.getTableData()
  }
}
</script>
